package com.jg.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.beanutils.BeanUtils;

import com.jg.dto.UserDTO;
import com.jg.entity.User;
import com.jg.service.IUser;


@Stateless(mappedName="userImplJndi")
public class UserImpl implements IUser {

	@PersistenceContext(unitName = "jg_ejb")
	private EntityManager entityManager;
	
	
	public void add(UserDTO userDto) {
		User user = new User();
		try {
			BeanUtils.copyProperties(user, userDto);
			user.setId(null);
			entityManager.persist(user);
		} catch (Exception e) {
			e.printStackTrace();
			new RuntimeException(e);
		}
	}


	public UserDTO get(Long id) {
		User user  = null;
		UserDTO userDto = null;
		try {
			user = (User) entityManager.find(User.class, id);
			userDto = new UserDTO();
			BeanUtils.copyProperties(userDto, user);
		} catch (Exception e) {
			new RuntimeException(e);
		}
		return userDto;
	}

	@SuppressWarnings("unchecked")
	public List<UserDTO> findAllUsers() {
		
		List<UserDTO> listaUserDto = new ArrayList<UserDTO>();
		List<User> listaUserEntity = (List<User>)entityManager.createQuery("from User u").getResultList();
		try {
//		PropertyUtils.copyProperties(listaUserDto, listaUserEntity);
		
			UserDTO userDTO = null;
			for (User user : listaUserEntity) {
				userDTO = new UserDTO();
				BeanUtils.copyProperties(userDTO, user);
				listaUserDto.add(userDTO);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			new RuntimeException(e);
		}
		return listaUserDto;
	}

}
